/**
 * Copyright (c) 2015-2030 by Beijing Yanlight Co., Ltd.
 * All rights reserved.
 */
package com.yanlight.util;

import java.io.File;

import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import com.yanlight.Constants;
import com.yanlight.type.TerminalType;

/**
 * 
 * @author haolw
 * @time 2017/12/18
 */
public abstract class FileUploadUtil {

	/**
	 * 
	 * @param file
	 * @return
	 */
	public static String processApk(String version, Integer type, MultipartFile file) {
		if (file == null) {
			return null;
		}
		String apkDir = Constants.APK_B_DIR;
		String appName = Constants.APP_B_NAME;
		if (TerminalType.C_NATIVE_CONSUMER.getType().equals(type)) {
			apkDir = Constants.APK_C_DIR;
		} else if (TerminalType.B_NATIVE_SUB_MERCHANT.getType().equals(type)) {
			apkDir = Constants.APK_B_S_DIR;
			appName = Constants.APP_B_S_NAME;
		}
		String absoluteDir = Constants.UPLOAD_APP_PATH.concat(apkDir);
		checkDir(absoluteDir);
		String fileName = appName + Constants.WHIFFLETREE + version + Constants.POINT + Constants.APK;
		String relativePath = recombinePath(apkDir, fileName);
		String absolutePath = recombinePath(absoluteDir, fileName);
		File targetFile = new File(absolutePath);
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return relativePath;
	}

	/**
	 * 
	 * @param file
	 * @return
	 */
	public static String processLogo(MultipartFile file) {
		if (file == null) {
			return null;
		}
		String relativeDir = Constants.LOGO_IMG_DIR;
		String absoluteDir = Constants.UPLOAD_PICTURE_PATH.concat(relativeDir);
		checkDir(absoluteDir);
		String fileName = recombineFileName(file);
		String relativePath = recombinePath(relativeDir, fileName);
		String absolutePath = recombinePath(absoluteDir, fileName);
		File targetFile = new File(absolutePath);
		try {
			file.transferTo(targetFile);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return relativePath;
	}

	/**
	 * 
	 * @param file
	 * @return
	 */
	private static String recombineFileName(MultipartFile file) {
		String name = FilenameUtils.getExtension(file.getOriginalFilename());
		String fileName = EncryptUtil.md5_16(ToolsUtil.uuid()) + Constants.POINT + name;
		return fileName;
	}

	/**
	 * 
	 * @param dir
	 * @param fileName
	 * @return
	 */
	private static String recombinePath(String dir, String fileName) {
		if (dir.endsWith(Constants.SLASH)) {
			return dir.concat(fileName);
		} else {
			return dir.concat(Constants.SLASH).concat(fileName);
		}
	}

	/**
	 * 
	 * @param dirPath
	 */
	private static void checkDir(String dirPath) {
		File dir = new File(dirPath);
		if (!dir.exists() && !dir.isDirectory()) {
			dir.mkdirs();
		}
	}

}
